//
//  GQHomeTitleView.m
//  GuQu
//
//  Created by HELIUM STAR on 15/5/8.
//  Copyright (c) 2015年 HELIUM STAR. All rights reserved.
//

#import "GQHomeTitleView.h"
#define kLineWidth 50

@interface GQHomeTitleView ()

@property (strong, nonatomic) NSMutableArray *lineViews;
@property (strong, nonatomic) UIView *selectedView;
@property (strong, nonatomic) NSMutableArray *lineWidths;

@end

@implementation GQHomeTitleView

- (NSArray *)lineWidths
{
    if (_lineWidths == nil) {
        _lineWidths = [NSMutableArray arrayWithObjects:@"40", @"40", @"40", nil];
    }
    return _lineWidths;
}

- (void)setItem:(NSArray *)item
{
    _item = item;
    [self setUpChildView];
    [self setSelectedIndex:0];
}

- (void)setUpChildView
{
    NSInteger count = self.item.count;
    CGFloat btnWidth = self.width / count;
    for (int i = 0; i < count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.width = btnWidth;
        btn.height = self.height;
        btn.x = btnWidth * i;
        btn.y = 0;
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitle:self.item[i] forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor clearColor]];
        [btn addTarget:self action:@selector(homeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i;
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        
        UIView *lineView = [[UIView alloc] init];
        lineView.width = [self.lineWidths[i] floatValue];
        lineView.height = 2;
        lineView.x = btn.width * i + (btn.width - [self.lineWidths[i] floatValue]) / 2;
        lineView.y = CGRectGetMaxY(btn.frame);
        lineView.backgroundColor = [UIColor whiteColor];
        lineView.alpha = 0;
        [self.lineViews addObject:lineView];
        
        [self addSubview:btn];
        [self addSubview:lineView];
    }
    
    
}


- (void)homeBtnClick:(UIButton *)button
{
    [self setSelectedIndex:button.tag];
    if ([_delegate respondsToSelector:@selector(homeTitleView:didClick:)]) {
        [_delegate homeTitleView:self didClick:button.tag];
    }
}

- (void)setSelectedIndex:(NSInteger)index
{
    self.selectedView.alpha = 0;
    UIView *lineView = self.lineViews[index];
    lineView.alpha = 1;
    self.selectedView = lineView;
}

- (NSMutableArray *)lineViews
{
    if (_lineViews == nil) {
        _lineViews = [NSMutableArray array];
    }
    return _lineViews;
}
@end
